package com.sws.models;

import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Repository("userDao")
@Transactional
public class UserDao  {
	private SessionFactory sessionFactory;
		
	@Autowired(required=true)
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
	
	@Transactional(readOnly = false)
	public void saveUser(User user) {
		sessionFactory.getCurrentSession().save(user);
	}
	
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<User> getAllUsers() {
		return (List<User>)sessionFactory.getCurrentSession().createCriteria(User.class).list();
	}
	
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public User getUserByEmail(String email)
	{
		List<User> userList = 
			(List<User>)sessionFactory.getCurrentSession().createCriteria(User.class).add(Restrictions.eq("email",email)).list();
		
		if (userList != null && userList.size() > 0)
		{
			return userList.get(0);
		}
		else
			return null;
	}

	@SuppressWarnings("unchecked")
	@Transactional(propagation=Propagation.REQUIRED)
	public void deleteUser(String id) {
		try{				
			User user = (User) sessionFactory.getCurrentSession().load(User.class, id);			
			List<RoleForUser> roles = sessionFactory.getCurrentSession().createCriteria(RoleForUser.class).add(Restrictions.eq("user.userId",id)).list();
			HibernateTemplate s = new HibernateTemplate(sessionFactory);
			s.deleteAll(roles);
			s.delete(user);				
			s.flush();
		}catch (Throwable e){
			e.printStackTrace();
		}
		
	}
}
